﻿using AutoUpdater.Entity;
using AutoUpdater.Util;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Net;

namespace PalletPrintProgram.Helper
{
    public class RestHttpHelper
    {
        public static TscResponse<T> PostJson<T>(string url,object data,Dictionary<string, string> headDict = null,int timeOut = 10000,bool writeLog = true)
        {
            try
            {
                var client = new RestClient(url);
                client.Timeout = 120000;

                string postDataString = "";
                if(data is string)
                {
                    postDataString = (string)data;
                }
                else
                {
                    postDataString = JsonHelper.ToJson(data);
                }

                var requestPost = new RestRequest("", RestSharp.Method.POST);

                if(headDict != null)
                {
                    foreach (var pair in headDict)
                    {
                        requestPost.AddHeader(pair.Key, pair.Value);
                    }
                }

                requestPost.AddParameter("application/json", postDataString, ParameterType.RequestBody);
                requestPost.Timeout = timeOut;

                IRestResponse responsePost = client.Execute(requestPost);

                if (responsePost.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    TscResponse<T> response = new TscResponse<T>();
                    response.code = -1;
                    response.message = responsePost.ErrorMessage + responsePost.Content + "错误";
                    return response;
                }
                else
                {
                    TscResponse<T> response = JsonHelper.ToObj<TscResponse<T>>(responsePost.Content);
                    return response;
                }
            }
            catch (Exception ex)
            {
                string Message = ex.Message;
                if (ex.InnerException != null)
                {
                    Message += ":" + ex.InnerException.Message;
                }
                TscResponse<T> response = new TscResponse<T>();
                response.code = -1;
                response.message = Message;
                return response;
            }
        }

        public static TscResponse<T> PostForm<T>(string url, Dictionary<string, string> keyValuePairs, Dictionary<string, string> webHeaderKeyValues = null, bool writeLog = true,int timeOut=10000)
        {
            try
            {
                var client = new RestClient(url);
                client.Timeout = timeOut;

                var requestPost = new RestRequest("", RestSharp.Method.POST);
                requestPost.Timeout = timeOut;

                if (webHeaderKeyValues != null)
                {
                    foreach (var pair in webHeaderKeyValues)
                    {
                        requestPost.AddHeader(pair.Key, pair.Value);
                    }
                }

                if (keyValuePairs != null)
                {
                    foreach (var pair in keyValuePairs)
                    {
                        requestPost.AddQueryParameter(pair.Key, pair.Value);
                    }
                }

                IRestResponse responsePost = client.Execute(requestPost);

                if (responsePost.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    TscResponse<T> response = new TscResponse<T>();
                    response.code = -1;
                    response.message = responsePost.ErrorMessage + responsePost.Content + "错误";
                    return response;
                }
                else
                {
                    TscResponse<T> response = JsonHelper.ToObj<TscResponse<T>>(responsePost.Content);
                    return response;
                }
            }
            catch (Exception ex)
            {
                string Message = ex.Message;
                if (ex.InnerException != null)
                {
                    Message += ":" + ex.InnerException.Message;
                }
                TscResponse<T> response = new TscResponse<T>();
                response.code = -1;
                response.message = Message;
                return response;
            }
        }

        public static byte[] DownloadFile(string url, object data, Dictionary<string, string> headDict = null, int timeOut = 100000, bool writeLog = true)
        {

            var restClient = new RestClient { BaseUrl = new Uri(url) };

            string postDataString = "";
            if (data is string)
            {
                postDataString = (string)data;
            }
            else
            {
                postDataString = JsonHelper.ToJson(data);
            }

            var requestPost = new RestRequest("", RestSharp.Method.POST);

            if (headDict != null)
            {
                foreach (var pair in headDict)
                {
                    requestPost.AddHeader(pair.Key, pair.Value);
                }
            }

            requestPost.AddParameter("application/json", postDataString, ParameterType.RequestBody);
            requestPost.Timeout = timeOut;

            byte[] byteArray = restClient.DownloadData(requestPost);
            return byteArray;
        }

        public static TscResponse<string> SendFile(string url, Dictionary<string, string> otherData, byte[] file1, string name, string contentType = null)
        {
            try
            {
                if (string.IsNullOrEmpty(contentType))
                {
                    contentType = "application/octet-stream";
                }

                var request = new RestRequest(Method.POST);

                if (otherData != null && otherData.Count > 0)
                {
                    foreach (var pare in otherData)
                    {
                        //传递参数
                        request.AddParameter(pare.Key, pare.Value);
                    }
                }

                //txtPictures.Text为文件路径
                request.AddFile("file", file1, name, contentType);
                //calling server with restClient
                var restClient = new RestClient { BaseUrl = new Uri(url) };
                //restClient.Timeout = 200;
                var response = restClient.Execute(request);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    try
                    {
                        //返回的路径和文件名集合，格式为["路径","文件名"]
                        string strResult = response.Content;
                        var result = JsonHelper.ToObj<TscResponse<string>>(strResult); 
                        return result;
                    }
                    catch (Exception ex)
                    {
                        return TscResponse<string>.Fail(ex.Message);
                    }
                }
                return TscResponse<string>.Fail(response.StatusCode.ToString()+ response.Content);
            }
            catch (Exception ex)
            {
                return TscResponse<string>.Fail(ex.ToString());
            }
        }

    }
}
